<template>
	<view>
		<view class="search-input"
			  id="search-input">
			<!-- 填充 -->
			<view :style="`height:${app.globalData.STATUS_BAR_HEIGHT}px`"></view>
			<view style="display: flex;">
				<up-icon name="arrow-left"
						 color="#DEDEDE"
						 size="48rpx"
						 @click="uni.navigateBack()"></up-icon>
				<up-search style="margin-left: 10rpx;"
						   @click="toSearchPage()"
						   shape="square"
						   placeholder="首拼/名称/编号/条码"
						   :clearabled="true"
						   :showAction="false"
						   bgColor="#4e77cf"
						   searchIconColor="#dedede"
						   placeholderColor="#DEDEDE"
						   color="#ffffff"
						   height="64rpx"
						   disabled></up-search>
				<up-icon style="margin-left: 10rpx;"
						 name="scan"
						 color="#DEDEDE"
						 size="54rpx"></up-icon>

			</view>
		</view>
		<!-- 填充 -->
		<view :style="{height:catagoryViewPaddingTop+'px'}"></view>
		<view class="category-view"
			  :style="{height:catagoryViewHeight+'px'}">
			<scroll-view class="category-left"
						 scroll-y>
				<view @click="itemLeftClick(index)"
					  v-for="(item,index) in brands"
					  :class="index==selectLeftIndex?'category-left-item-select':''"
					  class="category-left-item">
					<text>{{item.brand}}</text>
					<text v-if="car[item.brand]"
						  style="display: inline-flex;
								  margin-left: 10rpx;
								  width: 28rpx;  /* 直径尺寸 */
								  height: 28rpx; /* 必须与宽度相等 */
								  background-color: #FF5722; /* 背景色 */
								  border-radius: 50%; /* 关键属性 */
								  justify-content: center;
								  align-items: center;
								  color: #FFFFFF; /* 文字颜色 */">{{car[item.brand].length}}</text>
				</view>
			</scroll-view>
			<scroll-view style="background-color: #ffffff;"
						 class="category-right"
						 scroll-y>
				<view style="padding: 20rpx;border-bottom: 1px solid #dcdfe6;"
					  v-for="(item,index) in dataList"
					  @click="selectRightIndex = index">
					<view style="font-weight: bold;">{{item.pname}}</view>
					<view style="color: #75747c;position: relative;">
						<text>&nbsp</text>
						<text style="position: absolute;right: 0;">{{ item.bigunit?`￥${item.bigprice}\/${item.bigunit}`:`￥${item.smallprice}\/${item.smallunit}` }}</text>
					</view>
					<view v-show="index==selectRightIndex">
						<view style="display: flex;margin-top: 20rpx;"
							  v-if="item.bigunit"
							  v-for="(u_item,u_index) in item.itemList">
							<button v-if="u_item.saletype!='常规销售'"
									@click="showPopup( item)"
									style="display: flex;align-items: center; border:2rpx solid #000;border-radius: 50rpx;padding: 0 20rpx;margin-left: 0;background-color: #f3f2f7;"
									size="mini">
								<text style="padding: 0 20rpx;border-radius: 50%;background-color:#e36a4e ;color:#fff">{{u_item.saletype.slice(-1)}}</text>
								<text>{{`￥${u_item.unitprice}\/${u_item.unit}`}}</text>
								<up-icon name="arrow-down-fill"
										 style="margin-left: 10rpx;"></up-icon>
							</button>
							<button v-else
									style="display: flex;align-items: center; border:2rpx solid #000;border-radius: 50rpx;padding: 0 20rpx;margin-left: 0;background-color: #f3f2f7;"
									size="mini">
								<text>{{`￥${u_item.unitprice}\/${u_item.unit}`}}</text>
							</button>
							<up-number-box v-model="u_item.number"
										   buttonSize="25"
										   buttonWidth="25"
										   min="0"
										   @change="countChange($event,brands[selectLeftIndex].brand,index)"
										   integer></up-number-box>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>


		<!-- 0元赠弹出层 -->
		<popupGive :show="popupShow"
				   :productData="currentConfigProduct"
				   @close="popupClose"
				   @confirm="handleConfigConfirm"></popupGive>



		<view class="bottom-box"
			  id="bottom-box">
			<view style="padding: 20rpx;width: 160rpx;margin-left: auto;">
				<up-button type="primary"
						   @click="submitSelect()">添加({{carProductCount}})</up-button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		watch,
		computed,
		nextTick,
		getCurrentInstance
	} from 'vue'
	import {
		onReady,
		onLoad
	} from "@dcloudio/uni-app"
	const app = getApp()


	const catagoryViewHeight = ref(0)
	const catagoryViewPaddingTop = ref(0)
	onReady(() => {
		//.box获取class为box的元素，如果使用的id= 'box' 则使用'#box'
		uni.createSelectorQuery().select('#search-input').boundingClientRect(s_data => {
			uni.createSelectorQuery().select('#bottom-box').boundingClientRect(
				b_data => {
					catagoryViewPaddingTop.value = s_data.height
					catagoryViewHeight.value = app.globalData.SCREEN_HEIGHT -
						s_data.height - b_data.height
				}).exec()
		}).exec()
	})

	onLoad(async () => {
		// 可能上个页面有car传进来
		const eventChannel = getCurrentInstance().proxy.getOpenerEventChannel();
		eventChannel.on('setCar', (data) => {
			car.value = data
		})

		const res = await app.globalData.http.get("/wms/product/listbrand")
		brands.value = res.rows
		if (brands.value.length > 0) {
			itemLeftClick(0)
		}
	})

	const itemLeftClick = async (index) => {
		// 选中左边
		selectLeftIndex.value = index

		// 请求右边
		const params = {
			brand: brands.value[index].brand
		}
		const url = app.globalData.buildUrl("/wms/product/listsale", params)
		const res = await app.globalData.http.get(url)


		const car2list = Object.values(car.value).flat()
		res.rows.forEach((item) => {
			// 如果item.pid与car2list中某条数据的pid相同，则用某条数据的itemList覆盖item.itemList
			const matchedItem = car2list.find(carItem => carItem.pid === item.pid)
			if (matchedItem && matchedItem.itemList) {
				item.itemList = matchedItem.itemList
			}
		})
		dataList.value = res.rows
	}
	const toSearchPage = (index) => {
		uni.navigateTo({
			url: '/pages/searchPage'
		})
	}

	// 弹窗相关 - 简化后的代码
	const popupShow = ref(false)
	// 当前要配置的产品数据
	const currentConfigProduct = ref({})
	// 修改 showPopup 方法，直接接收并设置产品数据
	const showPopup = async (productData) => {
		currentConfigProduct.value = productData
		await nextTick();
		// 确保索引和产品数据同步
		popupShow.value = true
	}

	const popupClose = () => {
		popupShow.value = false
	}


	// 处理配置确认 - 替换原来的 sureGive 方法
	const handleConfigConfirm = async (configData) => {
		const {
			businessType,
			unit,
			unitPrice
		} = configData

		await nextTick();

		// 更新当前产品的itemList配置
		dataList.value[selectRightIndex.value].itemList.forEach((item, index) => {
			if (item.saletype != '常规销售') {
				item.unit = unit
				item.saletype = businessType
				item.unitprice = unitPrice
			}
		})

		// 修改car中的数据
		const brandId = brands.value[selectLeftIndex.value].brand

		// 确保该品牌的数组存在
		if (car.value[brandId]) {
			const productIndex = car.value[brandId].findIndex(cartItem =>
				cartItem.pid === dataList.value[selectRightIndex.value].pid
			)
			if (productIndex !== -1) {
				// 如果购物车中已存在此商品，更新它
				car.value[brandId][productIndex] = dataList.value[selectRightIndex.value]
			}
			console.log(car.value)
		}
	}





	// 左边选中
	const selectLeftIndex = ref(0)
	// 商品品牌，每一个商品品牌对应一个dataList
	const brands = ref([])

	// dataList中每一条记录都是一个商品，商品对象有个itemList数组属性，
	// itemList中每一条记录代表此商品的不同unit且每一条记录中都有一个number属性，是用户选择的数量)
	const dataList = ref([])
	// 右边选中
	const selectRightIndex = ref(0)
	// 购物车
	const car = ref({
		/*"一担粮": [
			{ pid: 10, pname: "壹号白酒", itemList: [{ unitprice: 10.5, number: 2 }] },
			{ pid: 11, pname: "花酒", itemList: [{ unitprice: 10.5, number: 2 }] },
		],
		"雪花": [
			{ pid: 121, pname: "天涯", itemList: [] },
		]*/
	})

	// 计算购物车中有多少种不同的商品
	const carProductCount = computed(() => {
		return Object.values(car.value).reduce((total, brandProducts) => {
			return total + brandProducts.length;
		}, 0);
	});


	// itemList数量变化 brandId为中文字符串如"一担粮",其实每一个商品中有一个brand字段
	const countChange = async (e, brandId, p_index, u_index) => {
		// 异步更新问题：Vue的响应式更新可能存在时机差异
		// 当我们使用p_index去访问对象的时候，极有可能双向绑定的itemList的number还未修改完毕
		// 此处可以优化，使用e.target.value来完成逻辑
		await nextTick();
		// 1. 检查当前商品的所有itemList的number是否都为0
		const allItemsZero = dataList.value[p_index].itemList.every(item => {
			// console.log('item.number:', item.number, 'type:', typeof item.number);
			return item.number === 0
		});
		if (allItemsZero) { // 2. 如果所有number都为0，从购物车中移除此商品
			if (car.value[brandId]) { // 如果所有number都为0，说明此前不是都为0，那么car中一定会有brandId
				const productIndex = car.value[brandId].findIndex(cartItem => cartItem
					.pid === dataList.value[p_index].pid);
				if (productIndex !== -1) { // 说明找到了
					car.value[brandId].splice(productIndex, 1);
					// 如果该品牌下没有商品了，删除整个品牌
					if (car.value[brandId].length === 0) {
						delete car.value[brandId];
					}
				}
			}
		} else { // 3. 如果不为0，更新购物车中对应的商品
			const selectedItems = dataList.value[p_index].itemList;
			// 确保该品牌的数组存在
			if (!car.value[brandId]) {
				car.value[brandId] = [];
			}

			// 查找该品牌下是否已存在此商品
			const productIndex = car.value[brandId].findIndex(cartItem => cartItem.pid ===
				dataList
				.value[p_index].pid);
			if (productIndex !== -1) { // 如果购物车中已存在此商品，更新它
				car.value[brandId][productIndex] = dataList.value[p_index];
			} else { // 如果购物车中不存在此商品，添加它
				car.value[brandId].push({
					...dataList.value[p_index]
				});
			}
		}
		console.log(car.value)
	}

	// 提交用户选中
	const submitSelect = () => {
		let pages = getCurrentPages()
		let prevPage = pages[pages.length - 2]; //上一页页面实例
		prevPage._.exposed.setCar(car.value)
		uni.navigateBack()
	}
</script>

<style lang="scss"
	   scoped>
	.search-input {
		background-color: #2757c5;
		width: auto;
		padding: 30rpx;
		position: fixed;
		left: 0;
		right: 0;
		z-index: 999;
	}

	.category-view {
		display: flex;

		.category-left {
			height: 100%;
			width: 200rpx;
			display: flex;
			flex-direction: column;
			background-color: #f3f2f7;
			color: #888693;

			.category-left-item {
				line-height: 2.5;
				text-align: center;

			}

			.category-left-item-select {
				background-color: #ffffff;
				color: #000;
			}

			// .category-left-item:last-of-type {
			// 	padding-bottom: 30rpx !important;
			// }
		}

		.category-right {
			height: 100%;
			flex: 1;
			background-color: #f6f6f6;

		}
	}

	.bottom-box {
		background-color: #ffffff;
		// height: 100rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		z-index: 998;
		box-sizing: content-box;
		border-top: 1px solid #dedede;
		padding-bottom: env(safe-area-inset-bottom);
	}
</style>